package com.github.itdachen.quartz.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 重点： 声明任务读取数据库
 *
 * @author 剑鸣秋朔
 * @date 2025/11/21 21:08
 */
@Configuration
public class SchedulerDataSourceConfig {
    private static final Logger logger = LoggerFactory.getLogger(SchedulerDataSourceConfig.class);

    private final QuartzJobFactory quartzJobFactory;

    public SchedulerDataSourceConfig(QuartzJobFactory quartzJobFactory) {
        this.quartzJobFactory = quartzJobFactory;
    }

    /***
     * 数据持久化，不然创建在内存中，服务关闭后重，需要重新建任务调度
     *
     * @author 剑鸣秋朔
     * @date 2025/11/21 21:08
     * @param dataSource spring 配置的数据源
     * @return org.springframework.scheduling.quartz.SchedulerFactoryBean
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("dataSource") DataSource dataSource) throws IOException {
        logger.info("schedulerFactoryBean ...");
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setDataSource(dataSource);
        factory.setJobFactory(quartzJobFactory);
        factory.setStartupDelay(2); // 启动之后多少秒开始执行，这里设置 2 秒
        return factory;
    }

}
